import { getUserOpenId, userLogin, getUserCloudPhone } from '../../services/usercenter/fetchPerson';
import { setOpenId, setSelectedSchoolId, setSelectedStudentId, setUserId, setSelectedSchoolData, getUserId, setStudentsList, getStudentsList, getOpenId, setSchoolList, getSchoolList, setRight, getSelectedSchoolData, getRight, setUserName, setUserPhone } from '../../userData/userData';
import { getSchoolFromCode, getAllStudent, addStudent, setDefaultStudent, getAllSchools, } from '../../services/students/studentData';
import Toast from 'tdesign-miniprogram/toast/index';
import { getStudentsPromise, clearStudentsPromise } from '../usercenter/students/edit/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    school: 0,
    schoolName: "",
    check: false,
    active: false,
    showSchool: false
    // 00000001
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initPrivacyCheck()//初始化隐私协议选择
    const arg = decodeURIComponent(options.q) // 获取到二维码原始链接内容
    let id = null
    if (arg && arg != 'undefined') {
      id = arg.split('?')[1].split('=')[1]
    }
    // id = '00000007'
    //id = '10000001'
    if (id) {
      //临时添加游客扫码进入
      if (id == 99999999) {
        this.onLoginTemp()
        return
      }
      //临时特殊学校登录代码
      if (id == "11111111") {
        this.onLoginTempSchool()
        return
      }
      //临时代码end
      this.setData({
        showSchool: true
      })
      getSchoolFromCode(id).then((schoolData) => {
        this.setData({
          school: schoolData.result[0]._id,
          schoolName: schoolData.result[0].name,
        })
        setSelectedSchoolData(schoolData.result[0])
        setSelectedSchoolId(schoolData.result[0]._id)
        if (getOpenId()) {
          getUserOpenId().then((data) => {
            setOpenId(data.result)
            this.onLoginUser()

          })
        }
        else {
          this.setData({
            active: true
          })
        }
      })
    }
    else {
      const schoolData = getSelectedSchoolData()
      if (schoolData.code) {
        //显示学校
        this.setData({
          showSchool: true
        })
        getSchoolFromCode(schoolData.code).then((schoolData) => {
          if (!schoolData.result[0]) {
            return
          }
          this.setData({
            school: schoolData.result[0]._id,
            schoolName: schoolData.result[0].name,

          })
          setSelectedSchoolData(schoolData.result[0])
          setSelectedSchoolId(schoolData.result[0]._id)
          if (getOpenId()) {
            this.onLoginUser()
          }
          else {
            this.setData({
              active: true
            })
          }
        })
      }
      else {
        this.setData({
          active: true
        })
        setRight("tourist")
        if (getOpenId()) {
          this.onLoginUser()
        }
      }

    }
    getAllSchools().then((res) => {
      const school = res.result
      let tempSchool = {}
      for (let index = 0; index < school.length; index++) {
        tempSchool[school[index]._id] = school[index]
      }
      setSchoolList(tempSchool)
    })

  },
  initPrivacyCheck() {
    if (getUserId()) {
      this.setData({
        check: true
      })
    }
  },
  handleRadioChange(e) {
    console.log(e)
    this.setData({
      check: e.detail.checked
    })
  },


  waitForNewStudents() {
    clearStudentsPromise()
    getStudentsPromise()
      .then((newStudents) => {
        newStudents.default = 1
        console.log(newStudents)
        addStudent(newStudents).then((data) => {
          let studentList = getStudentsList()
          const schoolDate = getSchoolList()
          data.result[0].schoolName = schoolDate[data.result[0].i_id].name
          studentList.push(data.result[0])
          setStudentsList(studentList)
          setSelectedStudentId(data.result[0]._id)
          setSelectedSchoolId(data.result[0].i_id)
          wx.switchTab({
            url: '/pages/home/home',
            success: (res) => { },
            fail: (res) => { },
            complete: (res) => { },
          })
        })
      })
      .catch((e) => {
        this.setData({
          active: true
        })
        wx.navigateBack({ delta: 1 });
        if (e.message !== 'cancel') {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '子女编辑发生错误',
            icon: '',
            duration: 1000,
          });
        }
      });
  },

  onLogin(e) {
    this.setData({
      active: false
    })
    if (!e.detail.iv) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '授权失败',
      });
      this.setData({
        active: true
      })
      return
    }

    getUserOpenId().then((data) => {
      setOpenId(data.result)
      this.onLoginUser(e)

    })
  },
  onLoginUser(e) {
    if (!this.data.check) {
      return
    }

    this.setData({
      active: false
    })
    userLogin().then((userData) => {
      setUserId(userData.result[0]._id)
      setUserName(userData.result[0].username)
      getAllStudent().then((studentList) => {
        console.log(studentList.result.length, userData.result[0].username == "", !e)
        if (getRight() == "tourist" && studentList.result.length == 0) {
          wx.switchTab({
            url: '/pages/goods/category/index',
            success: (res) => { },
            fail: (res) => { },
            complete: (res) => { },
          })
          return
        }

        const schoolDate = getSchoolList()
        studentList.result.forEach(element => {
          element.schoolName = schoolDate[element.i_id].name
        });
        setStudentsList(studentList.result)
        if (studentList.result.length == 0) {
          if (userData.result[0].username == "") {
            if (!e) {
              this.setData({
                active: true
              })
              return
            }
            else {
              getUserCloudPhone(e).then((res) => {
                console.log(res)
                setUserPhone(res.result)
                wx.navigateTo({
                  url: '/pages/register/index'
                });
              }).catch((e) => {
                Toast({
                  context: this,
                  selector: '#t-toast',
                  message: '获取手机号失败，如果微信未绑定手机号请前去绑定！',
                  icon: '',
                  duration: 1000,
                });
                this.setData({
                  active: true
                })
                return
                // wx.navigateTo({
                //   url: '/pages/register/index'
                // })
              });
            }

          }
          else {
            this.waitForNewStudents()
            wx.navigateTo({
              url: '/pages/usercenter/students/edit/index'
            });
          }
        }
        else {
          this.onLoginHome(studentList)
        }
      })
    }).catch((e) => {
      console.log(e)
      this.setData({
        active: true
      })
    })
  },
  onLoginHome(studentList) {
    let isDefault = false
    studentList.result.forEach(element => {
      if (element.i_id == this.data.school || getRight() == "tourist") {
        if (element.default == 1) {
          isDefault = true
          setSelectedStudentId(element._id)
          setSelectedSchoolId(element.i_id)
          if (getRight() == "tourist") {
            const schoolDate = getSchoolList()
            setSelectedSchoolData(schoolDate[element.i_id])
          }
          setRight("school")
          wx.switchTab({
            url: '/pages/home/home',
            success: (res) => { },
            fail: (res) => { },
            complete: (res) => { },
          })
        }
      }
    });
    if (!isDefault) {
      this.waitForNewStudents()
      wx.navigateTo({
        url: '/pages/usercenter/students/edit/index'
      });
    }
  },
  openPrivacy() {
    wx.navigateTo({
      url: '/pages/privacyAgreement/index'
    });
  },
  //临时login
  onLoginTemp() {
    setRight("tourist")
    userLogin().then((userData) => {
      setUserId(userData.result[0]._id)
      setUserName(userData.result[0].username)
      wx.switchTab({
        url: '/pages/goods/category/index',
        success: (res) => { },
        fail: (res) => { },
        complete: (res) => { },
      })
    }).catch((e) => {
      console.log(e)
      this.setData({
        active: true
      })
    })
  },
  onLoginTempSchool() {
    getAllSchools().then((res) => {
      const school = res.result
      let tempSchool = {}
      for (let index = 0; index < school.length; index++) {
        tempSchool[school[index]._id] = school[index]
      }
      setSchoolList(tempSchool)
      getUserOpenId().then((data) => {
        setOpenId(data.result)
        userLogin().then((userData) => {
          setUserId(userData.result[0]._id)
          setUserName(userData.result[0].username)
          wx.redirectTo({
            url: '/pages/usercenter/school/index',
          });
        }).catch((e) => {
          console.log(e)
          this.setData({
            active: true
          })
        })
      })
    })

  }
})